package autoFile.main;

import autoFile.annotation.AutoFile;
import autoFile.core.strategy.interfaces.CreateFileStrategyInterface;
import autoFile.enums.CreateDbsFileEnum;
import autoFile.enums.CreateGasFileEnum;
import com.google.common.collect.Lists;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: liuliwei
 * Date: 2017-08-16
 * Time: 下午5:20
 * Description: ${description}
 */
public class GasAutoApp {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, IOException {

      doMain();

    }

    public static void doMain() throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                new String[]{"classpath*:gas/application-context-gas*.xml"});
        createFileFromApplicationContextAndAnnotation(ctx);
    }

    /**
     * 调用 此方法可以生成
     * @param ctx
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws IOException
     */
    public static void createFileFromApplicationContextAndAnnotation(ClassPathXmlApplicationContext ctx) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException {
        CreateFileStrategyInterface createFileStrategy;
        deleteFile();
        Map<String, Object> beans = ctx.getBeansWithAnnotation(AutoFile.class);
        for (Object o : beans.values()) {
            Class clazz= o.getClass();
            String className = clazz.getName();
            if (className.contains("$")) {
                int $Index = clazz.getName().indexOf("$");
                 clazz = Class.forName(className.substring(0, $Index));
            }

            for (CreateGasFileEnum createFileEnum : CreateGasFileEnum.values()) {
                createFileStrategy= (CreateFileStrategyInterface) createFileEnum.getValue().newInstance();
                createFileStrategy.createFile(clazz);

            }
        }
    }

    private static void deleteFile() {
        File autoFile = new File("/Users/liuliwei/autoFile");
        File gas = new File("/Users/liuliwei/autoFile/gas");
        List<File> fileList = Lists.newArrayList();
        fileList.add(gas);
        fileList.add(autoFile);
        for (File file : fileList) {
            File[] files = file.listFiles();
            for (File file1 : files) {
                if (!file1.isDirectory()) {
                    System.out.println("delete file"+file1.getName());
                    file1.delete();
                }
            }
        }
        System.out.println("######################");
    }
}
